package jeeobserver.server;

import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import jeeobserver.server.Statistics.Element;

final class DatabaseFileElements<T extends DatabaseFileElements.DatabaseElementEntity> extends DatabaseFile.DatabaseFileVariableRecord {

	 DatabaseFileElements(String path, Class<T> type) throws IOException {
			super(path + ".dat", type);
	 }

	 public void persist(Collection<DatabaseElementEntity> elements) throws IOException {

			this.reset();

			Object entity;

			Set<Integer> elementIds = new HashSet<Integer>();
			while ((entity = this.read()) != null) {
				 if (((DatabaseElementEntity) entity).getStatus() == DatabaseElementEntity.STATUS_ACTIVE) {
						elementIds.add(((DatabaseElementEntity) entity).getElement().getId());
				 }
			}

			//If element not exists insert
			for (DatabaseElementEntity element : elements) {
				 if (!elementIds.contains(element.getElement().getId())) {
						this.append(element);
				 }
			}
	 }

	 public abstract static class DatabaseElementEntity implements DatabaseEntity {

			public static final byte STATUS_ACTIVE = 0;

			public static final byte STATUS_DELETED = 1;

			private byte status;

			public DatabaseElementEntity(byte status) {
				 this.status = status;
			}

			public byte getStatus() {
				 return status;
			}

			public void setStatus(byte status) {
				 this.status = status;
			}

			public abstract Element getElement();
	 }
}